package com.activemq;

import java.util.concurrent.ConcurrentHashMap;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.netty.DiscardServerHandler;
import com.netty.HeartbeatServer;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

/**
 * 消息的消费者（接受者）
 *
 */
public class JMSConsumer {

	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;// 默认连接用户名
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;// 默认连接密码
	private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;// 默认连接地址

	public static void main(String[] args) {
		
		ConnectionFactory connectionFactory;// 连接工厂
		Connection connection = null;// 连接

		Session session;// 会话 接受或者发送消息的线程
		Topic topic;// 消息的目的地

		MessageConsumer messageConsumer;// 消息的消费者

		// 实例化连接工厂
		connectionFactory = new ActiveMQConnectionFactory(JMSConsumer.USERNAME, JMSConsumer.PASSWORD,
				JMSConsumer.BROKEURL);

		try {
			new HeartbeatServer().start();
			// 通过连接工厂获取连接
			connection = connectionFactory.createConnection();
			// 启动连接
			connection.start();
			// 创建session
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			topic = session.createTopic("myTopic.messages");
			// 创建消息消费者
			messageConsumer = session.createConsumer(topic);
			while (true) {
				TextMessage textMessage = (TextMessage) messageConsumer.receive(100000);
				if (textMessage != null) {
					ConcurrentHashMap<String, ChannelHandlerContext> channelMap = DiscardServerHandler.channelMap;
					if(channelMap.size() > 0){
						ChannelHandlerContext  ctx = channelMap.get("0001120113211009");
						Channel channel = ctx.channel();
						int i = 2000;
						// 把int转换为字节数组
						byte[] result = new byte[4];
						result[0] = (byte) (i >>> 24);// 取最高8位放到0下标
						result[1] = (byte) (i >>> 16);// 取次高8为放到1下标
						result[2] = (byte) (i >>> 8); // 取次低8位放到2下标
						result[3] = (byte) (i); // 取最低8位放到3下标
						ByteBuf encoded = ctx.alloc().buffer();
						encoded.writeBytes(result);
						encoded.retain();
						channel.write(encoded);
						channel.flush();
					}
					System.out.println("收到的消息:" + textMessage.getText());
				} else {
					break;
				}
			}
			
		} catch (JMSException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}

	}
}